package com.dhcc.bpm.modules.develop.service.impl;

import com.dhcc.bpm.common.exception.BusinessException;
import com.dhcc.bpm.common.utils.database.ScrewExportDatabaseUtils;
import com.dhcc.bpm.modules.develop.service.DatabaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @program: cbus-bpm-boot
 * @ClassName DatabaseService
 * @description: TODO
 * @author: xiafayu
 * @create: 2022-05-25 16:59:00
 * @Version 1.0.0
 **/
@Service
public class DatabaseServiceImpl implements DatabaseService {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseServiceImpl.class);
    @Value("${bpm.file-public-path}")
    String filePath;
    @Value("${bpm.dictData.version}")
    String version;
    @Value("${bpm.dictData.description}")
    String description;
    @Value("${bpm.dictData.fileName}")
    String fileName;
    @Autowired
    ScrewExportDatabaseUtils screwExportDatabaseUtils;

    @Override
    public void createDataDict(String tableName, HttpServletResponse response) {
        File file = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".html", "utf-8"));

            file = new File(filePath + fileName + ".html");
            if(!file.exists()){
                screwExportDatabaseUtils.createContextLoads(tableName);
            }
            fileResponse(file, response);

        } catch (UnsupportedEncodingException e) {
            logger.error("生成数据字典失败:{}", e);
            throw new BusinessException("导出数据字典文档失败!");
        }


    }

    public void fileResponse(File file, HttpServletResponse response){
        byte[] buffer = new byte[4096];
        try (FileInputStream bis = new FileInputStream(file)) {
            OutputStream os = response.getOutputStream();
            int bytesRead = -1;
            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        } catch (Exception e) {
            logger.error("导出数据字典异常：{}", e);
        }
        screwExportDatabaseUtils.contextLoads();
    }

}
